import re
import Seqitem


class Parse:
    """A class to parse genome Data."""

    def __init__(self, file, mode):
        self.file_name = file
        self.mode = mode


    def run(self):
        """ A function to prepare Data for downstream applications"""
        file = open(self.file_name, "r")
        raw_data = file.read().replace("\n", "")
        data = re.split(">", raw_data)

        for i in data:
            yield self.format_data(i)

    def return_MATCHES(self, p, s):
        """ A helper function to find the matches in the formated Data"""
        l = []
        for m in re.finditer(p, s):
            if m is not None:
                l.append(m)
            else:
                return None
        return l

    def format_data(self, inp):
        if inp is not None:
            m = self.return_MATCHES(
                "hg19_ct_UserTrack_3545_(.+) range=(chr.+):(\d+)-(\d+) 5'pad=\d+ 3'pad=\d+ strand=. repeatMasking=none(\w+)", inp)
                #"hg19_(.+) range=chr(.+):\d+-\d+ 5'pad=\d+ 3'pad=\d+ strand=. repeatMasking=none(\w+)", inp)
            #
            for i in m:
                return Seqitem.Item(i.group(1), i.group(5), i.group(2), i.group(3), i.group(4))

    def motif_finder(self, motif, feature_gen):
        motif = motif.lower()
        motif = self.iupac(motif)

        print "Searching for %s" % motif

        mem_list = []
        for feature in feature_gen:
            self.match_list = []
            if feature is not None:

                for match in re.finditer(motif, feature.seq):
                    if match is not None and (not feature.name in mem_list):

                        self.match_list.append(match)
                mem_list.append(feature.name)

            if len(self.match_list) > 0:
                yield [feature, self.match_list]
            # Returns feature name and sequence and matches in a list
    def iupac(self,sequence):
        seq = sequence
        seq = seq.replace("n","[a|t|c|g]")
        seq = seq.replace("w","[a|t]")
        seq = seq.replace("s","[c|g]")
        seq = seq.replace("m","[a|c]")
        seq = seq.replace("k","[t|g]")
        seq = seq.replace("r","[a|g]")
        seq = seq.replace("y","[t|c]")
        return seq
